<template>
    <l-layout class="l-tab-page" v-show="!lr_loadPage" >
        <template #left>
            <l-panel :title="$t('菜单管理-功能目录')" style="padding-right:0;" >
                <el-tree v-loading="loading" :data="modulesExpandTree" :expand-on-click-node="false"  @node-click="handleNodeClick">
                    <span class="lr-tree-node"  slot-scope="{ node, data }">
                        <i :class="data.icon"></i>
                        {{ $t(node.label) }}
                    </span>
                </el-tree>
            </l-panel>
        </template>
        <l-panel style="padding-left:0;" >
            <template #toolLeft >
                <div class="l-panel--item" >
                    <el-input :placeholder="$t('请输入编码/名称')"  @keyup.enter.native="hanleSearch" v-model="searchWord" size="mini" >
                        <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </div>
            </template>
            <template #toolRight >
                <l-tool-btns @click="handleAdd()" >
                </l-tool-btns>
            </template>
            <l-table 
                :columns="lr_getPageColumns(columns)" 
                :dataSource="searchTableData || tableData" 
                :loading="loading" >
                <template v-slot:f_EnabledMark="scope" >
                    <el-switch
                        :active-value="1"
                        :inactive-value="0"
                        v-model="scope.row.f_EnabledMark"
                        @change="handleEnableChange(scope.row)"
                        >
                    </el-switch>
                </template>
                <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick" ></l-table-btns>
            </l-table>
        </l-panel>

        <l-dialog 
            :title="formTitle"
            :visible.sync="formVisible"
            :height="440"
            @ok="handleSave"
            @close="handleCloseForm"
            @opened="handleOpenedForm"
            >
            <my-form ref="form" :f_ParentId="currentModuleId" ></my-form>       
        </l-dialog>

    </l-layout>
</template>

<script>
import { mapGetters } from "vuex"
import MyForm from './form'


export default {
    inject: ["admin"],
    components: {
        MyForm
    },
    data () {
        return {
            lr_isPage:true,
            //查询
            searchWord:'',
            searchTableData:null,

            loading:false,
            columns: [
                {label:'编号',prop:'f_EnCode',width:'140'},
                {label:'名称',prop:'f_FullName',width:'120'},
                {label:'地址',prop:'f_UrlAddress',minWidth:'240'},
                {label:'目标',prop:'f_Target',width:'100',align:'center',formatter:function({cellValue}){
                    switch(cellValue){
                        case 'expand':
                            return '菜单目录';
                        case 'view':
                            return '功能页面';
                        case 'custmerForm':
                            return '自定义功能';
                        case 'desktop1':
                        case 'desktop0':
                            return '桌面设计';
                        default:
                            return cellValue;
                    }
                }},
                {label:'排序',prop:'f_SortCode',width:'64',align:'center'},
                {label:'状态',prop:'f_EnabledMark',width:'64',align:'center'}
            ],
            tableBtns:[
                {prop:'Edit',label:'编辑'},
                {prop:'Delete',label:'删除'}
            ],

            currentModuleId:'0',
            formVisible:false,
            formTitle:'',
            formEditRow:null,
            isEdit:false,

            custmerFormVisible:false,
            stepActive: 0,

            deskVisible:false,
            deskStepActive:0,
            deskId:''

        };
    },
    computed:{
        ...mapGetters(["modulesExpandTree","modulesGroup"]),
        tableData(){
            const tableData = this.modulesGroup[this.currentModuleId] || []
            return tableData//.filter(t=>t.f_Target != 'custmerForm')
        }
    },
    mounted () {
        this.updateModules()
    },
    methods:{
        updateModules(){
            this.loading = true
            this.$store.dispatch("system/module/getList").then(()=> {
                this.loading = false
                this.admin.refreshMenu()
            })
        },
        hanleSearch(){
            if(this.searchWord){
                this.searchTableData = this.tableData.filter(item => item.f_FullName.indexOf(this.searchWord) >-1 || item.f_EnCode.indexOf(this.searchWord)>-1);
            }
            else{
                this.searchTableData = null;
            }
        },
        handleNodeClick(data) {
            this.currentModuleId = data.id
        },
        removeTableData(index){
            if(this.searchTableData){
                if(!this.$validatenull(this.modulesGroup[this.searchTableData[index].f_ModuleId])){
                    this.$message({
                        type: 'warning',
                        message: '有子菜单无法删除!'
                    });
                    return false;
                }
                this.searchTableData.splice(index,1);
            }
            else{
                if(!this.$validatenull(this.modulesGroup[ this.modulesGroup[this.currentModuleId][index].f_ModuleId])){
                    this.$message({
                        type: 'warning',
                        message: '有子菜单无法删除!'
                    });
                    return false;
                }
                this.modulesGroup[this.currentModuleId].splice(index,1);
            }

            return true;
        },
        handleEnableChange(row){
            this.$store.dispatch("system/module/updateState",{id:row.f_ModuleId,state:row.f_EnabledMark}).then(()=> {
                this.$message({
                    type: 'success',
                    message: '更新成功!'
                });
                this.admin.refreshMenu()
            })
        },
        handleAdd(){
            this.isEdit = false;
            this.showForm('新增功能')
        },
        handleEdit($index,row){
            this.formEditRow = row
            if(row.f_Target == 'custmerForm'){
                this.custmerFormVisible = true
            }
            else if(row.f_Target.indexOf('desktop') != -1){
                this.formTitle = `编辑移动桌面-${row.f_FullName}`
                this.deskVisible = true
            }
            else{
                this.isEdit = true
                this.showForm('编辑功能')
            }
           
        },
        handleDelete($index,row){
            this.$confirm(this.$t('此操作将永久删除该数据, 是否继续?'), this.$t('提示'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
            }).then(() => {
                if(this.removeTableData($index)){
                    this.$store.dispatch("system/module/remove",row.f_ModuleId).then(()=> {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                        this.admin.refreshMenu()
                    })
                }
            }).catch((err) => {
                console.log(err,'err')
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })       
            })
        },
        handleSave(showLoading,hideLoading){
            showLoading()
            this.$refs.form.validateForm((valid)=>{
                if(!valid){
                    hideLoading()
                    return
                }
                const postData = this.$refs.form.getForm();
                if(this.isEdit){// 修改数据
                    this.$store.dispatch("system/module/update",{id:this.formEditRow.f_ModuleId,formData:postData}).then(()=> {
                        hideLoading();
                        this.formVisible = false;
                        this.$message({
                            type: 'success',
                            message: '更新成功!'
                        });
                        this.admin.refreshMenu();
                    }).catch(() => {
                        hideLoading();
                    })
                }
                else{// 新增数据
                    this.$store.dispatch("system/module/add",postData).then(()=> {
                        hideLoading();
                        this.formVisible = false;
                        this.$message({
                            type: 'success',
                            message: '添加成功!'
                        });
                        this.admin.refreshMenu();
                    }).catch(() => {
                        hideLoading();
                    })
                }
            })
        },
        handleOpenedForm(showLoading,hideLoading){
            if(this.isEdit){
                showLoading('加载数据中...')
                this.$store.dispatch("system/module/get",this.formEditRow.f_ModuleId).then((res)=> {
                    this.$refs.form.setForm(res)
                    hideLoading()
                }).catch((err)=>{
                    console.log(err)
                    this.$message({
                        type: 'warning',
                        message: '获取编辑数据失败!'
                    })
                    hideLoading()
                    this.formVisible = false
                })    
            }
        },
        handleCloseForm(){
            this.$refs.form.resetForm()
        },
        showForm(text){
            this.formTitle = text
            this.formVisible = true
        }
    }
}
</script>
